package com.serkol.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.serkol.openai.Role;
import com.serkol.openai.RoleDeserializer;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.io.IOException;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
//@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        return objectMapper;
    }
    @Bean
    public SimpleModule jsonModule() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Role.class,
                new StdDeserializer<Role>(Role.class) {
                    @Override
                    public Role deserialize(JsonParser p, DeserializationContext ctxt)
                            throws IOException {
                        return StringUtils.hasText(p.getValueAsString()) ?
                                Role.valueOf(p.getValueAsString()) :
                                null;
                    }
                });
        return module;
    }
    @Bean
    public SimpleModule javaTimeModule() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(OpenAiApi.ChatCompletionMessage.Role.class, new RoleDeserializer());
        return module;
    }
/*@Bean
public SimpleModule javaTimeModule() {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Role.class, new JsonDeserializer<Role>() {
        @Override
        public Role deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            System.out.println(p.getValueAsString());
            return Role.fromValue(p.getValueAsString());
        }
    });
    return module;
}*/
/*    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        mapper.registerModule(new SimpleModule()
                .addDeserializer(OpenAiApi.ChatCompletionMessage.Role.class, new RoleDeserializer()));
        return mapper;
    }*/
}
